package com.hmsm.sys.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;

import com.hmsm.server.base.BaseAction;
import com.hmsm.server.common.CommonUtil;
import com.hmsm.server.util.QueryResult;
import com.hmsm.sys.po.DynamicCipherCard;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.service.DynamicCipherCardService;

/**
 *  @Description:
 *  @ClassName  :com.hmsm.sys.action.DynamicCipherCardAction.java
 *  @Author     :yaosq
 *  @CreateDate :2013-11-15 下午01:28:22  
 **/
@Controller
public class DynamicCipherCardAction extends BaseAction<UserInfo> {
   
	private static final long serialVersionUID = 4539890661614785694L;
	
	@Resource
	private DynamicCipherCardService dynamicCipherCardService;
	
	public DynamicCipherCardService getDynamicCipherCardService() {
		return dynamicCipherCardService;
	}
	public void setDynamicCipherCardService(DynamicCipherCardService dynamicCipherCardService) {
		this.dynamicCipherCardService = dynamicCipherCardService;
	}

	private String snJson;//SN json对象
	private List<DynamicCipherCard> snInfolist;
	private int snCode;
	private int isBinding;
	private String nowpage = null;// 页码
	private String maxpage = null;// 每页显示条数	
	private int count;
	private int allPages;
	private int page;//当前页
	private int rowsPage;//每页数量
	private QueryResult<DynamicCipherCard> result;// 密令集合
	private int loginType;
	private File upload;
	private String msg;
	
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public int getLoginType() {
		return loginType;
	}
	public void setLoginType(int loginType) {
		this.loginType = loginType;
	}
	public int getIsBinding() {
		return isBinding;
	}
	public void setIsBinding(int isBinding) {
		this.isBinding = isBinding;
	}
	public String getNowpage() {
		return nowpage;
	}
	public void setNowpage(String nowpage) {
		this.nowpage = nowpage;
	}
	public String getMaxpage() {
		return maxpage;
	}
	public void setMaxpage(String maxpage) {
		this.maxpage = maxpage;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getAllPages() {
		return allPages;
	}
	public void setAllPages(int allPages) {
		this.allPages = allPages;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getRowsPage() {
		return rowsPage;
	}
	public void setRowsPage(int rowsPage) {
		this.rowsPage = rowsPage;
	}
	public QueryResult<DynamicCipherCard> getResult() {
		return result;
	}
	public void setResult(QueryResult<DynamicCipherCard> result) {
		this.result = result;
	}
	public String getSnJson() {
		return snJson;
	}
	public void setSnJson(String snJson) {
		this.snJson = snJson;
	}
	
	public List<DynamicCipherCard> getSnInfolist() {
		return snInfolist;
	}
	public void setSnInfolist(List<DynamicCipherCard> snInfolist) {
		this.snInfolist = snInfolist;
	}
	
	public Integer getSnCode() {
		if(snCode==0){
			return null;
		}else{
			return snCode;
		}
	}
	public void setSnCode(Integer snCode) {
		if(snCode!=null){
			this.snCode = snCode;
		}
	}
	/**
     * 
     *  @Description: 获取sn树形结构
     *  @MethodName :snInfoTree
     *  @Author     :yaosq
     *  @CreateDate :2013-11-15 上午11:15:32 
     *  @return
     *
     */
	public String snInfoTree(){
		//获取所有未绑定的sn信息
		snInfolist = this.getDynamicCipherCardService().getDynamicInfo();
		StringBuffer sb = new StringBuffer();
		sb.append("[");
			for(int i=0;i<snInfolist.size();i++){
				DynamicCipherCard dynaCard = snInfolist.get(i);
				if(i > 0){
					sb.append(",");
				}
				sb.append("{pkId:\""+dynaCard.getPkId()+"\",name:\""+dynaCard.getSnCode()+"\"}");
			}
		sb.append("]");
		snJson = sb.toString();
		return SUCCESS;
	}
	
	/**
	 * 
	 *  @Description:修改sn密令信息分配标志
	 *  @MethodName :updateSNInfo
	 *  @Author     :yaosq
	 *  @CreateDate :2013-11-15 下午04:44:41 
	 *  @param sn
	 *
	 */
	public String updateSNInfo(){
		 this.getDynamicCipherCardService().updateSNInfo(snCode);
		 mapResult.put("success", true);
		 return "json";
	}
	 
	/**
	 * 
	 *  @Description:解除绑定
	 *  @MethodName :jcSNInfo
	 *  @Author     : LZYYJ
	 *  @CreateDate :2013-11-15 下午06:35:42 
	 *  @param sn
	 *
	 */
	public String jcSNInfo(){
		try {
			this.getDynamicCipherCardService().jcSNInfo(snCode);
			 mapResult.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			 mapResult.put("success", false);
			 mapResult.put("errorMessage", ""+e.getMessage());
		}
		return "json";
	}
	 
	 /**
	 *  @Description:获取snCode列表
	 *  @MethodName :manage 原名 getSnCodeList
	 *  @Author     :fengt
	 *  @CreateDate :2013-11-19 下午12:01:39 
	 *  @return
	 **/
	public String manage(){
		UserInfo user = getSessionUser();
		if (user == null ) {
			this.setMessage("当前用户已失效，请重新登录！");
			return ERROR;
		}
		if (page==0) {
			page = 1;// 当前页数
		}
		if (rowsPage==0) {
			rowsPage = 10;// 每页显示数
		}
		if (nowpage != null && !nowpage.trim().equals("")) {
			page = Integer.parseInt(nowpage.trim());
			if (page == 0) {
				page = 1;
			}
		}
		if (maxpage != null && !maxpage.trim().equals("")) {
			rowsPage = Integer.parseInt(maxpage.trim());
		}
		
		count = this.getDynamicCipherCardService().getDynamicInfoCount(snCode, isBinding);
		allPages = count%rowsPage == 0?count/rowsPage:count/rowsPage+1;//获得总页数
		result = this.getDynamicCipherCardService().getDynamicInfoList(page, rowsPage, allPages, snCode, isBinding, count);
		if (result == null) {
			snInfolist = new ArrayList<DynamicCipherCard>();
		}else{
			snInfolist = result.getResultlist();
		}
		
		loginType = CommonUtil.loginType;

		return SUCCESS;
	}
	
	/**
	 *  @Description:上传密令卡
	 *  @MethodName :uploadSnCode
	 *  @Author     :fengt
	 *  @CreateDate :2013-11-19 下午04:18:57 
	 **/
	public String uploadSnCode(){
		 try {
             if(upload.exists()){ //判断文件是否存在
            	 Map<Integer, String> map = new HashMap<Integer, String>();
            	 List<DynamicCipherCard> hasCardList = getDynamicCipherCardService().getDynamicCipherCardDao().queryAll();
            	 for (DynamicCipherCard card : hasCardList) {
            		 if(card != null){
            			 map.put(card.getSnCode(), card.getSnInfo());
            		 }
				 }
            	 List<DynamicCipherCard> cardList = new ArrayList<DynamicCipherCard>();
                 InputStreamReader read = new InputStreamReader( new FileInputStream(upload),"GBK");//考虑到编码格式
                 BufferedReader bufferedReader = new BufferedReader(read);
                 String lineTxt = null;
                 while((lineTxt = bufferedReader.readLine()) != null){
                     if(StringUtils.isNotBlank(lineTxt)){
                    	 String[] line = lineTxt.split(",");
                    	 if (map.get(Integer.valueOf(line[0])) == null) {
							DynamicCipherCard card = new DynamicCipherCard();
							card.setSnCode(Integer.valueOf(line[0]));
							card.setSnInfo(line[1]);
							card.setIsBinding(0);//未绑定
							cardList.add(card);
							//保存到已经添加的map
							map.put(Integer.valueOf(line[0]), line[1]);
						}
                     }
                 }
                 read.close();
                 //持久化
                 for (DynamicCipherCard card : cardList) {
					getDynamicCipherCardService().save(card);
				 }
             }else{
            	 this.msg = "-1";
            	 return ERROR;
             }
		 } catch (Exception e) {
	         e.printStackTrace();
	         this.msg = "-2";
	         return ERROR;
		 }
		 this.msg = "1";
		 return SUCCESS;
	}
}
